package converter.util

import org.apache.commons.exec.CommandLine
import org.apache.commons.exec.DefaultExecutor
import org.apache.commons.exec.PumpStreamHandler

class EffectivePomProducer {

	private Map env

	EffectivePomProducer(Map env) {
		this.env = env
	}

	private CommandLine buildCommandLine(File pom, File output) {
		String effectivePomFileName = output.getAbsolutePath()
		boolean isWindows = ((String) System.properties['os.name']).toLowerCase().contains("win")
		String mvnExe =  isWindows ? "mvn.bat" : "mvn"
		if(env) {
			if(isWindows) {
				mvnExe = env['M2_HOME'] +  "\\" + "bin" + "\\"  + mvnExe
			}else {
				mvnExe = env['M2_HOME'] +  "/" + "bin" + "/"  + mvnExe
			}
		}
		//println "The Maven path[$mvnExe]"
		CommandLine cmdLine = new CommandLine(mvnExe);
		cmdLine.addArgument("-f")
		cmdLine.addArgument(pom.getAbsolutePath())
		cmdLine.addArgument("-Doutput=${effectivePomFileName}")
		cmdLine.addArgument("help:effective-pom")
		return cmdLine

	}

	private File buildTmpOutputFile(String prefix) {
		return File.createTempFile(prefix, ".effective-pom.xml")
	}

	File getEffectivePom(File pom){
		ByteArrayOutputStream baos = new ByteArrayOutputStream()
		ByteArrayOutputStream errorStream = new ByteArrayOutputStream()
		File output = buildTmpOutputFile(pom.hashCode().toString())
		output.deleteOnExit()
		CommandLine cmdLine = buildCommandLine(pom, output)
		DefaultExecutor executor = new DefaultExecutor()
		executor.setStreamHandler(new PumpStreamHandler(baos, errorStream, System.in))
		int exitValue
		if(env) {
			//exitValue = executor.execute(cmdLine,env);
			exitValue = executor.execute(cmdLine);
		}else {
			exitValue = executor.execute(cmdLine);
		}
		if( exitValue != 0 ) {
			println errorStream.toString()
			assert false : "Generation of effective pom for [" + pom.absolutePath + "]"
		}
		return output
	}
}
